package com.miaoxun.web.shiro;

import com.miaoxun.domain.entity.User;
import com.miaoxun.service.MenuService;
import com.miaoxun.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;


public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Autowired
    MenuService menuService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        User user = userService.findByUsername(((User) principalCollection.getPrimaryPrincipal()).getUsername());

        Set<String> perms = menuService.listPerms((user.getUserId()));

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {

        String username = (String) token.getPrincipal();
        if (username == null || "".equalsIgnoreCase(username)) {
            throw new UnknownAccountException("账号不正确");
        }
        String password = new String((char[]) token.getCredentials());
        // 查询用户信息
        User user = userService.findByUsername(username);
        // 账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        // 密码错误
        if (!user.getPassword().equalsIgnoreCase((password))) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }
        // 账号锁定
        if (user.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }

}